/* (L) Kirilyuk Artur, 2012 */
var VKReady = false;
var controls = {};
var timers = {};
var debug = true;

var chat = {
    room : 0,
    send : function () {
        var msg = $.trim(controls.chatinput.val());
        VK.api('sendMessage',
            {message: msg},
            function (data) {
                log(data);
                controls.chatinput.val("");
            }
        );
    },
    receive : function () {
        VK.api('getMessages',
            function (data) {
                log(data);
                if (!data.response || !data.response[0])
                    return;
                for (var msg in data.response) {
                    var msgObj = data.response[msg];
                    var toAdd = msgObj.user_name + ': ' + msgObj.message + '\n';
                    controls.chathistory.val(controls.chathistory.val() + toAdd);
                }
            }
        );
    }
}

function log (data) {
    if (debug) {
        console.info (arguments.callee.caller.name || log.caller || "Caller is unknown");
        console.log(data);
    }
}

function init() {
    log('Init!');
    controls.container = $('#container');
    controls.chathistory = $('<textarea id="chathistory"></textarea>').appendTo(controls.container);
    controls.chatinput = $('<input type="text" id="chatinput" maxlength="127"/>').appendTo(controls.container)
                            .keydown(function (event) {
                                if (event.which == 13)
                                    chat.send();
                            });
    controls.chatsubmit = $('<input type="button" id="chatsubmit" value="\>\>\>" />').appendTo(controls.container)
                            .click(function() {
                                chat.send();
                            });
    setInterval(chat.receive, 1000);
}



VK.init(function (){
    VKReady = true;
});

$(document).ready(function () {
    timers.VKReady = setInterval(function () {
        if (VKReady) {
            clearInterval(timers.VKReady);
            init();
        }
    }, 100);
});